import { getBatchSessions } from '@/api/chat'

const state = {
  sessions: [],
  lastFetch: null
}

const mutations = {
  SET_SESSIONS(state, sessions) {
    state.sessions = sessions
    state.lastFetch = Date.now()
  }
}

const actions = {
  async fetchSessions({ commit }, roles) {
    try {
      const body = { personaIds: roles }
      const resp = await getBatchSessions(body)
      if (resp && resp.sessions) {
        commit('SET_SESSIONS', resp.sessions)
      }
    } catch (error) {
      console.error('获取会话失败', error)
      ElMessage.error('会话加载失败')
    }
  }
}

const getters = {
  getSessionByInitials: (state) => (initials) => {
    return state.sessions.find(s => s.personaInitials === initials)
  },
  shouldRefresh: (state) => {
    // 30分钟缓存有效期
    return !state.lastFetch || (Date.now() - state.lastFetch) > 30 * 60 * 1000
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}